<template>
    <a-modal :visible="state.visible" title="Basic Modal" @cancel="handleCancel" @ok="handleOk" width="100%"
        wrapClassName="full-modal">
        <AForm ref="formRef" :model="state.formData" :labelCol="{ style: 'width:120px' }">
            <ARow>
                <ACol :span="8">
                    <AFormItem label="优惠券标题" :rules="{required:true,message:'必填'}" name="title">
                        <AInput v-model:value="state.formData.title"></AInput>
                    </AFormItem>
                </ACol>
            </ARow>
            <ARow>
                <ACol :span="8" >
                    <AFormItem label="优惠券图片" name="imageUrl" :rules="{required:true,message:'必填'}">
                        <UploadImage v-model:value="state.formData.imageUrl"></UploadImage>
                    </AFormItem>
                </ACol>
            </ARow>
            <ARow>
                <ACol :span="8">
                    <AFormItem label="参与人群" :rules="{required:true,message:'必填'}" name="crowdRange">
                        <a-radio-group v-model:value="state.formData.crowdRange" name="crowdRang">
                            <a-radio :value="CrowdRangeEnum.ALL">所有用户</a-radio>
                            <a-radio :value="CrowdRangeEnum.NEW">新会员</a-radio>
                            <a-radio :value="CrowdRangeEnum.MEMBER">其他会员</a-radio>
                        </a-radio-group>
                    </AFormItem>
                </ACol>
            </ARow>
            <ARow>
                <ACol :span="8">
                    <AFormItem label="门槛类型" :rules="{required:true,message:'必填'}" name="threshold">
                        <ASelect v-model:value="state.formData.threshold">
                            <ASelectOption :value="thresholdEnum.Amount">满金额</ASelectOption>
                            <ASelectOption :value="thresholdEnum.Quantity">满数量</ASelectOption>
                        </ASelect>
                    </AFormItem>
                </ACol>
                <ACol :span="8">
                    <AFormItem label="门槛" :rules="{required:true,message:'必填'}" name="thresholdNum">
                        <AInput v-model:value="state.formData.thresholdNum" :suffix="state.formData.threshold==1?'元':'件'"></AInput>
                    </AFormItem>
                </ACol>
            </ARow>
            <ARow>
                <ACol :span="8">
                    <AFormItem label="是否和促销叠加" :rules="{required:true,message:'必填'}" name="withPromo">
                        <a-radio-group v-model:value="state.formData.withPromo" name="withPromo">
                            <a-radio :value="1">是</a-radio>
                            <a-radio :value="2">否</a-radio>
                        </a-radio-group>
                    </AFormItem>
                </ACol>


            </ARow>
            <ARow>
                <ACol :span="8">
                    <AFormItem label="优惠类型" :rules="{required:true,message:'必填'}" name="type">
                        <ASelect v-model:value="state.formData.type" @change="handleTypeChange">
                            <ASelectOption :value="preferentialEnum.Discount">打折</ASelectOption>
                            <ASelectOption :value="preferentialEnum.Subtraction">减钱</ASelectOption>
                        </ASelect>
                    </AFormItem>
                </ACol>
                <ACol :span="8" :rules="{required:true,message:'必填'}">
                    <AFormItem v-if="state.formData.type==preferentialEnum.Subtraction" label="优惠数值" name="value">
                        <a-input v-model:value="state.formData.value" suffix="元"></a-input>
                    </AFormItem>
                    <AFormItem v-if="state.formData.type==preferentialEnum.Discount" label="优惠数值" name="value">
                        <a-input v-model:value="state.formData.value" suffix="折"></a-input>
                    </AFormItem>
                </ACol>
            </ARow>
            <a-row>
                <a-col :spn="8" :rules="{required:true,message:'必填'}">
                    <AFormItem label="发放数量" name="quantity">
                        <AInput v-model:value="state.formData.quantity"></AInput>
                    </AFormItem>
                </a-col>
            </a-row>
            <a-row>
                <a-col :span="8">
                    <AFormItem label="领取数量" name="takeCount">
                        <AInput v-model:value="state.formData.takeCount"></AInput>
                    </AFormItem>
                </a-col>
                <a-col :span="8">
                    <AFormItem label="已使用数量" name="usedCount">
                        <AInput v-model:value="state.formData.usedCount"></AInput>
                    </AFormItem>
                </a-col>
            </a-row>
            <a-row>
                <a-col :span="8">
                    <AFormItem label="时效类型" :rules="{required:true,message:'必填'}" name="validType">
                        <a-radio-group v-model:value="state.formData.validType" name="withPromo">
                            <a-radio :value="1">按设置的日期</a-radio>
                            <a-radio :value="2">按领取后的天数</a-radio>
                        </a-radio-group>
                    </AFormItem>
                </a-col>
                <a-col v-if="state.formData.validType==1" :span="8">
                    <AFormItem label="时效类型" :rules="{required:true,message:'必填'}" name="validType">
                        <DateRangePicker v-model:start="state.formData.validStartTime"
                            v-model:end="state.formData.validEndTime" />
                    </AFormItem>
                </a-col>
                <a-col v-if="state.formData.validType==2" :rules="{required:true,message:'必填'}" :span="8">
                    <AFormItem label="领取后多少天失效" name="usedCount">
                        <AInput v-model:value="state.formData.validDays"></AInput>
                    </AFormItem>
                </a-col>
            </a-row>
            <a-row>
                <a-col :span="8">
                    <AFormItem label="参与商品" :rules="{required:true,message:'必填'}" name="scope">
                        <a-radio-group v-model:value="state.formData.scope" name="scope">
                            <a-radio :value="scopeEnum.WholeOrder">整单</a-radio>
                            <a-radio :value="scopeEnum.Category">品类</a-radio>
                            <a-radio :value="scopeEnum.Single">单品</a-radio>
                        </a-radio-group>
                    </AFormItem>    
                </a-col>
            </a-row>
            <a-row v-if="state.formData.scope==scopeEnum.Category">
                <a-col :span="24">
                <AFormItem   label="参与品类"
                    name="categories"
                    :rules="[{required:true,message:'请选择',trigger:'change'}]"
                    >
                            <a-select v-model:value="state.formData.categories" allowClear mode="multiple">
                    <a-select-option v-for="(categoryItem,categoryItemIndex) in state.goodsCategoryOptions" 
                    :key="categoryItemIndex" 
                    :value="categoryItem.goodsCategoryId">
                        {{ categoryItem.goodsCategoryName}}
                    </a-select-option>
                    </a-select>
                    </AFormItem>
                </a-col>
            </a-row>            
            <a-row  v-if="state.formData.scope==scopeEnum.Single">
                <a-col :span="24">
                    <AFormItem 
                    label="参与商品"
                    name="goods"
                    :rules="[{required:true,message:'请选择'}]">
            <div class="mb-10">
                <a-button type="primary" @click="addFormGoods">添加参与商品</a-button>
            </div>
            <a-table :data-source="state.formData.goods" :pagination="false">
                <a-table-column key="goodsCode" data-index="goodsCode"  title="商品编码">
                    <template #default="{record}">{{ record.goodsCode }}</template>
                </a-table-column>
                <a-table-column key="goodsName" data-index="goodsName"  title="商品名称">
                    <template #default="{record}">{{ record.goodsName }}</template>
                </a-table-column>
                <a-table-column key="originalPrice" data-index="originalPrice"  title="原始价格">
                    <template #default="{record}">{{ record.originalPrice }}</template>
                </a-table-column>
                <a-table-column key="salePrice" data-index="salePrice"  title="销售价格">
                    <template #default="{record}">{{ record.salePrice }}</template>
                </a-table-column>
                <a-table-column key="salePrice" data-index="salePrice"  title="操作">
                    <template #default="{record,index}">
                        <a-button @click="removeGoodsItem(record,index)">移除</a-button>
                    </template>
                </a-table-column>
            </a-table>
        </AFormItem>    
                </a-col>
            </a-row>    
        </AForm>
    </a-modal>
    <GoodsModal  
        v-if="state.goodsModalVisible"
        @ok="receiveGoods" 
        @cancel="state.goodsModalVisible = false"></GoodsModal>
</template>
<script lang="ts" setup>
import { ResponseVo, CouponTypes, CrowdRangeEnum, thresholdEnum, preferentialEnum, scopeEnum, GoodsCategoryTypes, GoodsTypes } from "../../../type";
import { reactive, ref, onMounted } from "vue";
import UploadImage from "@/components/UploadImage/UploadImage.vue"
import DateRangePicker from "@/components/DateRangePicker/index.vue";
import { CouponService, GoodsCategoryService } from "@/service";
import { message } from "ant-design-vue";
import ARow from "ant-design-vue/lib/grid/Row";
import { GoodsModal } from "@/components/index";

type ICouponModal = Partial<CouponTypes.ICouponItem>& {
        validStartTime:string;
        validEndTime:string;
    }

const props = withDefaults(defineProps<{
    currentCoupon?: Partial<CouponTypes.ICouponItem>;
}>(), {
    currentCoupon: () => ({
        validStartTime:"",
        validEndTime:""
    })
})

const formRef = ref()
const emit = defineEmits<{
    (e: "ok"): void,
    (e: "cancel"): void
}>()

const state = reactive<{
    formData: ICouponModal;
    visible: boolean,
    goodsCategoryOptions:GoodsCategoryTypes.GoodsCategoryItem[];
    goodsModalVisible: boolean;
}>({
    formData: {
        validStartTime:"",
        validEndTime:""
    },
    visible: true,
    goodsCategoryOptions:[],
    goodsModalVisible: false
})

onMounted(() => {
    state.formData = { ...props.currentCoupon } as ICouponModal;
    console.log("state.formData--->",state.formData)
    getGoodsCategory();
})

const getGoodsCategory = async()=>{
    const res:ResponseVo<GoodsCategoryTypes.GoodsCategoryItem[]>= await GoodsCategoryService.findAllGoodsCategory();
    if(res.code===0){
        state.goodsCategoryOptions = res.data;
    }
}

const handleOk = () => {
    formRef.value.validateFields().then(async (valid: boolean) => {
        if (valid) {
            let res: ResponseVo<any>
            if (state.formData.id) {
                res = await CouponService.editCoupon(state.formData as CouponTypes.ICouponItem);
            } else {
                res = await CouponService.addCoupon(state.formData as CouponTypes.ICouponItem);
            }
            if (res.code === 0) {
                message.success("操作成功！")
                emit("ok");
            }
        }
    })
}

const handleCancel = () => {
    emit("cancel")
}

const handleTypeChange = ()=>{
    state.formData.value = undefined;
}

const addFormGoods = ()=>{
        state.goodsModalVisible = true;
    }

    const removeGoodsItem = (record:Partial<GoodsTypes.IGoodsItem>,index:number)=>{
        state.formData.goods?.splice(index,1);
    }

    const receiveGoods = (values:any)=>{
        state.goodsModalVisible = false;
        if(state.formData.goods===undefined)state.formData.goods=[];
        state.formData.goods.push(...values);
        console.log("state.formData.goods--->",state.formData.goods)
    }
</script>